//
//  HWFeedBackViewController.m
//  HWanGame
//
//  Created by 陈道斌 on 2019/10/17.
//  Copyright © 2019 Chendaobin. All rights reserved.
//

#import "HWFeedBackViewController.h"
#import "LFOpinionView.h"
#import "HWLoginController.h" 
#define MAX_LIMIT_NUMS 120

@interface HWFeedBackViewController ()<UITextViewDelegate>
@property(strong,nonatomic)UIView *typeofProblemView;
@property(strong,nonatomic)UIView *opinionView;
@property (nonatomic, strong) LFOpinionView *textView;
@property(strong,nonatomic)UIButton *seleBut;
@property(strong,nonatomic)UIButton *tiajianButton;
@property(strong,nonatomic) UITextField *phoneTextField;
@property(strong,nonatomic) NSString *jianyipingtaiStr;
@end

@implementation HWFeedBackViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    
}

- (void)setupUI {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"意见反馈";
    
    [self addTypeOfProblemView];
    
    //意见反馈
    [self appOpinionView];
    
    
    
}

// 添加TypeView
- (void)addTypeOfProblemView {
    
    self.typeofProblemView = [[UIView alloc]initWithFrame:CGRectMake(0, NavBarHeight, kScreenW, 84)];
 //   self.typeofProblemView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.typeofProblemView];
    
    
      UILabel *xuanzaLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 0, 200, 45)];
      xuanzaLabel.text = @"请选择问题类型";
      xuanzaLabel.font = [UIFont systemFontOfSize:13];
      xuanzaLabel.textColor = RGB(51, 51, 51);
      [self.typeofProblemView addSubview:xuanzaLabel];
    
//       UIButton *butt  = [UIButton setButtonWithFrame:CGRectMake(line*50+hengjianju*(line*2+1), shujianju*row+shujianju+row*50, 50, 50) Title:self.listArr[i] Image:self.icoArr[i] Font:12 Color:RGB(51, 51, 51) Target:self Selector:@selector(buttonTap:)];
//        butt.tag = i;
//        [butt layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleTop imageTitleSpace:20];
//      // butt.backgroundColor = [UIColor redColor];
//        [self addSubview:butt];
    
    NSArray *titileArr = @[@"App建议",@"游戏相关",@"其他问题"];
    NSArray *icoArr =  @[@"cus_cir_b",@"cus_cir",@"cus_cir"];

    for (int i = 0; i < 3; i++) {
        
        UIButton *butt  = [UIButton setButtonWithFrame:CGRectMake(16+19*i + 85*i,49, 85, 20) Title:titileArr[i] Image:icoArr[i] Font:12 Color:RGB(51, 51, 51) Target:self Selector:@selector(buttonTap:)];
        butt.tag = i;
        [butt layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:10];
        if (i == 0 ) {
            self.seleBut  = butt;
            self.jianyipingtaiStr = @"1";
        }
      //  butt.backgroundColor = [UIColor yellowColor];
        [self.typeofProblemView addSubview:butt];
        
        
    }
    
    
    
    UIView *fengexian = [[UIView alloc]initWithFrame:CGRectMake(0, 83, kScreenW, 1)];
    fengexian.backgroundColor = RGB(232, 232, 242);
    [self.typeofProblemView addSubview:fengexian];
    
    
    
}



// 设置UIBUtton
- (void)buttonTap:(UIButton *)sender {
    
    int  tap = (int )sender.tag;
    
    if (tap == 0) {
        self.jianyipingtaiStr = @"1";
    } else if (tap == 1) {
        
        self.jianyipingtaiStr = @"2";
    } else {
        
         self.jianyipingtaiStr = @"3";
    }
    
   // [self.seleBut setBackgroundImage:[UIImage imageNamed:@"cus_cir"] forState:UIControlStateNormal];
    [self.seleBut setImage:[UIImage imageNamed:@"cus_cir"] forState:UIControlStateNormal];
    self.seleBut = sender;
    [self.seleBut setImage:[UIImage imageNamed:@"cus_cir_b"] forState:UIControlStateNormal];
    
    
    
    
    
}

//添加View
- (void)appOpinionView {
    
    
    self.opinionView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.typeofProblemView.bottom, kScreenW, 48+110)];
    self.opinionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview: self.opinionView];
    
    
    UILabel *xuanzaLabel = [[UILabel alloc]initWithFrame:CGRectMake(16, 0, 200, 48)];
    xuanzaLabel.text = @"请输入您的反馈：";
    xuanzaLabel.font = [UIFont systemFontOfSize:13];
    xuanzaLabel.textColor = RGB(51, 51, 51);
    [self.opinionView addSubview:xuanzaLabel];
    
    UIView *basieview = [[UIView alloc]initWithFrame:CGRectMake(17, xuanzaLabel.bottom-1, kScreenW-17*2, 110)];
    basieview.backgroundColor = [UIColor whiteColor];
    basieview.layer.borderWidth = 1;
    basieview.layer.borderColor = RGB(232, 232, 242).CGColor;
    [self.opinionView  addSubview:basieview];
    
    
    
     _textView = [[LFOpinionView alloc] init];
     _textView.alwaysBounceVertical = YES;
     _textView.delegate = self;
//     _textView.x = 10;
//     _textView.y = 0;
     _textView.frame = CGRectMake(10, 0, kScreenW- 20-34, 110);
     _textView.backgroundColor = [UIColor whiteColor];
     _textView.textColor = RGB(51, 51, 51);
     _textView.placeholder = @"我们将为您不断改进";
     _textView.font = [UIFont systemFontOfSize:14];
     [basieview addSubview:_textView];
    
    
    self.phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(17, self.opinionView.bottom+10,  kScreenW-17*2, 40)];
     self.phoneTextField.placeholder = @"请输入手机号";
      
      self.phoneTextField.keyboardType = UIKeyboardTypePhonePad;
      self.phoneTextField.textColor = RGB(51, 51, 51);
      self.phoneTextField.font = [UIFont systemFontOfSize:13];
      self.phoneTextField.borderStyle =UITextBorderStyleNone;
      self.phoneTextField.layer.borderWidth = 1;
      self.phoneTextField.layer.borderColor = RGB(230, 239, 233).CGColor;
      self.phoneTextField.layer.cornerRadius = 6;
      self.phoneTextField.layer.masksToBounds = YES;
      UIView *youbinview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 35)];
      self.phoneTextField.leftView = youbinview;
      self.phoneTextField.leftViewMode = UITextFieldViewModeAlways;
     [self.view addSubview:self.phoneTextField];
       
    
    
     self.tiajianButton  = [UIButton buttonWithType:UIButtonTypeCustom];
     self.tiajianButton.layer.cornerRadius = 17;
     self.tiajianButton.layer.masksToBounds = YES;
     self.tiajianButton.frame = CGRectMake((kScreenW-120)/2, self.phoneTextField.bottom+10, 120, 35);
    
     self.tiajianButton.backgroundColor = blueBackgroundBT;
     [self.tiajianButton  setTitle:@"提交" forState:UIControlStateNormal];
     [self.tiajianButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     [self.tiajianButton addTarget:self action:@selector(tiajianButtonTap) forControlEvents:UIControlEventTouchUpInside];
     [self.view addSubview:self.tiajianButton];
    
    

}


#pragma mark --------- 点击提交按钮
- (void)tiajianButtonTap {
    
    DLog(@"dgyidguhdosojp");
    
    if ([[HWLocallyStoredData getLoginUserID] isEqualToString:@""]) {
               HWLoginController  *login = [[HWLoginController alloc]init];
                 [self.navigationController pushViewController:login animated:YES];
                return;
         
    }
    
    
    if(!(self.textView.text.length >  0)) {
        
        [MBProgressHUD showError:@"反馈内容不能为空"];
        return;
        
    } else if (!(self.phoneTextField.text.length > 0)){
        
        
        [MBProgressHUD showError:@"手机号不能为空"];
        return;
        
    }
    
    
    
    
    
    
       NSString *uidStr = [NSString stringWithFormat:@"%@",[HWLocallyStoredData getLoginUserID]];
       NSString *tStr = [NSString stringWithFormat:@"%ld",[WMUtil getTimeSp]];
       
       NSString *typeStr =  [NSString stringWithFormat:@"%@",self.jianyipingtaiStr];
       
       NSString *singStr = [NSString stringWithFormat:@"%@%@%@",uidStr,tStr,@"fsd213ewdsadqwe2121213edsad"];
       
       NSString *singMD5 = [WMUtil md5HexDigest:singStr];
    
       NSString *phoneStr = [NSString stringWithFormat:@"%@",self.phoneTextField.text];
       NSString *contentStr = [NSString stringWithFormat:@"%@",self.textView.text];
     
 
    
       NSDictionary *parametes = @{
            
                                           @"ios" : @"1",
                                           @"ct" :  @"app",
                                           @"ac" : @"service",
                                           @"uid" :uidStr,
                                           @"t" : tStr,
                                           @"type" :typeStr,
                                           @"sign" : singMD5,
                                           @"phone" :phoneStr,
                                           @"content" :contentStr
                                           };
           
          [HWWebUtils doGetWithParameters:parametes progress:nil success:^(id response) {
               
             
               
               NSString *codeStr =  [NSString stringWithFormat:@"%@",response[@"code"]];
               
               if ([codeStr intValue] == 1) {
            
               
                   [self.navigationController popViewControllerAnimated:YES];
                     [MBProgressHUD showError:response[@"message"]];
                   
                   
        
        
               } else {
                   
                   
                    [MBProgressHUD showError:response[@"message"]];
                   
               }
            
               
               
           } failure:^(NSString *error) {
              
                 [MBProgressHUD showError:@"发送建议失败"];
               
           }];
    
    
    
    
    
    
    
    
    
    
    
    
}



 
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


//第一个方法用于限制输入，第二个方法用于动态计算剩余字数
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range

 replacementText:(NSString *)text

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    //获取高亮部分内容

    //NSString * selectedtext = [textView textInRange:selectedRange];

    

    //如果有高亮且当前字数开始位置小于最大限制时允许输入

    if (selectedRange && pos) {

        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];

        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];

        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);

        

        if (offsetRange.location < MAX_LIMIT_NUMS) {

            return YES;

        }

        else

        {
            [MBProgressHUD showError:@"最多只能输入120个字符"];

            return NO;

        }

    }

    

    

    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];

    

    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;

    

    if (caninputlen >= 0)

    {

        return YES;

    }

    else

    {

        NSInteger len = text.length + caninputlen;

        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错

        NSRange rg = {0,MAX(len,0)};

        

        if (rg.length > 0)

        {

            NSString *s = @"";

            //判断是否只普通的字符或asc码(对于中文和表情返回NO)

            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];

            if (asc) {

                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错

            }

            else

            {

                __block NSInteger idx = 0;

                __block NSString  *trimString = @"";//截取出的字串

                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个

                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])

                                         options:NSStringEnumerationByComposedCharacterSequences

                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {

                                          

                                          if (idx >= rg.length) {

                                              *stop = YES; //取出所需要就break，提高效率

                                              return ;

                                          }

                                          

                                          trimString = [trimString stringByAppendingString:substring];

                                          

                                          idx++;

                                      }];

                

                s = trimString;

            }

            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)

            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];

            //既然是超出部分截取了，哪一定是最大限制了。

         //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%d个字",0];

        }
        
        
         [MBProgressHUD showError:@"最多只能输入120个字符"];

        return NO;

    }

    

}

 

- (void)textViewDidChange:(UITextView *)textView

{

    UITextRange *selectedRange = [textView markedTextRange];

    //获取高亮部分

    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];

    

    //如果在变化中是高亮部分在变，就不要计算字符了

    if (selectedRange && pos) {

        return;

    }

    

    NSString  *nsTextContent = textView.text;

    NSInteger existTextNum = nsTextContent.length;

    

    if (existTextNum > MAX_LIMIT_NUMS)

    {

        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)

        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];

        

        [textView setText:s];

    }

    

    //不让显示负数

 //   self.remainLabel.text = [NSString stringWithFormat:@"您最多还可以输入%ld个字",MAX(0,MAX_LIMIT_NUMS - existTextNum)];

}



@end
